import { useEffect, useState } from "react"
import style from './index.module.scss'
import { Modal, Form, Input, Button, message } from "antd"
import { ShowRoleFnc, EditRoleFnc } from '@/api/roles'
import { itemType } from "./type"
import PropTypes from "prop-types"

const EditRoles = ({isModalOpen, changeDialog, id, roleName, roleDesc, init}: itemType) => {
  // 获取form实例, 用来清空form
  const [form] = Form.useForm()

  // 用于做比较的form
  const [formObj, setFormObj] = useState({})

  // 数据初始化
  const initFnc = async () => {
    if(id !== '') {
      const res = await ShowRoleFnc(parseInt(id), {roleId: parseInt(id), roleName: roleName, roleDesc: roleDesc})
      if(res.data.meta.status === 200) {
        form.setFieldsValue({roleName: roleName, roleDesc: roleDesc})
        setFormObj({roleName: roleName, roleDesc: roleDesc})
      }
    }
  } 
  useEffect(() => { initFnc() }, [id]) 

  // 修改表单
  const onFinish = async (info: {roleName: string, roleDesc: string}) => {
    if(JSON.stringify(formObj) === JSON.stringify(info)) {
      changeDialog(false)
    } else {
      const res =  await EditRoleFnc(parseInt(id), info)
      if(res.data.meta.status === 200) {
        message.success('更新成功', 1.5,  () => {
           changeDialog(false)
           init()
        })
      }
    }
  }
  return (
    <Modal title='编辑角色' open={isModalOpen} footer={null} onCancel={() => changeDialog(false)}>
       <Form form={form} className={style.form} onFinish={onFinish} labelCol={{ span: 4 }}>
          <Form.Item name="roleName" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }, {min: 3, max: 10, message: '长度在3-10个字符'}]}>
            <Input/>
          </Form.Item>
            
          <Form.Item name="roleDesc" label="角色描述" rules={[{required: true, message: '请输入角色描述'}, {min: 3, max: 10, message: '长度在3-10个字符'}]}>
            <Input/>
          </Form.Item> 
           

          <Form.Item style={{marginBottom: 0}}>
            <div className={style.btn}>
              <Button type="primary" htmlType="submit">修改</Button>
              <Button type="default" onClick={() =>changeDialog(false)}>取消</Button>
            </div>
          </Form.Item>
        </Form>
    </Modal>
  )
}

export default EditRoles
EditRoles.proTypes = {
  isModalOpen: PropTypes.bool.isRequired,
  changeDialog: PropTypes.func.isRequired,
  id: PropTypes.string.isRequired,
  roleName: PropTypes.string.isRequired,
  roleDesc: PropTypes.string.isRequired,
  init: PropTypes.func.isRequired,
}